<?php
namespace app\beautiful\logic;
use app\beautiful\model\order\CashierOrderItemModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\OnceCardOrderModel;
use app\beautiful\model\order\PinTuanOrderItemModel;
use app\beautiful\model\order\SnapUpOrderModel;
use app\beautiful\model\order\StoreOrderModel;
use app\beautiful\model\partner\PartnerSettingModel;
use app\beautiful\model\partner\PartnerShareModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\SmsLogic;
use think\Model;

class PartnerLogic {
    private  $setting;
    private  $shopId;
    public function __construct($shopId) {
        $this->setting = PartnerSettingModel::where('shop_id',$shopId)->find();
        $this->shopId = $shopId;
    }

    /**
     * @params $memberId,$money 
     * @return  bool
     * 停用此方法
     */
    public function  commission_bak($memberId,$money){
        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        if($money <= 0) return false;
        $pid  = $mid = 0; $mobile = '';
        if(is_numeric($memberId)){
            $member = MemberModel::find($memberId);
            if(null === $member) return false;
            $pid = $member->pid;
            $mid = $memberId;
        }else{
            $pid = $memberId->pid;
            $mid = $memberId->member_id;
        }
        if(empty($pid)) return false;
        $pmemberModel = new MemberModel();
        if(null === $pmember = $pmemberModel->find($pid)) return false;
        $partner = PartnerModel::where([
            ['mobile','=',$pmember->mobile],
            ['shop_id','=', $this->shopId],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;
        switch($partner->role_id){
            case 1: //股东
                return  $this->shareholderCommission($partner, $mid, $money);
                break;
            case 2://员工
                return  $this->staffCommission($partner, $mid, $money);
                break;
            case 3://会员
                return  $this->memberCommission($partner, $mid, $money);
                break;
            case 4://自定义
                return  $this->customCommission($partner, $mid, $money);
                break;
        }
        return true;
    }
    //员工业绩
    private function staffCommission($partner,$mid,$money,$orderTypeName,$description,$orderId=0){
        if(empty($this->setting->commission_data)) return false;
        $month = date('Y-m',time());
        $sum = PartnerCommissionModel::where([
            ['shop_id','=', $this->shopId],
            ['partner_id','=',$partner->partner_id],
            ['month','=',$month]
        ])->sum('monetary');
        $nowMoney = round(($sum*100 + $money * 100)/100,2);
        //start_achievement
        $commissionRate = 0;
        foreach($this->setting->commission_data as $val){
            if($nowMoney >= $val['start_achievement'] && $val['commission'] >= $commissionRate){
                $commissionRate = $val['commission'];
            }
        }
        if(empty($commissionRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = 0; //不可提现
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'description' => $description,
            'type'       => $orderTypeName,
            'date' => date('Y-m-d H:i:s',time()),
            'order_id'=>$orderId,
        ]);
        return true;
    }
    //会员推广员业绩
    private function  memberCommission($partner,$mid,$money,$orderTypeName,$description,$orderId=0){
        $commissionRate = $this->setting->commission;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = round(($partner->withdrawable_profit *  100  + $commission * 100)/100,2);
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'description' => $description,
            'type'       => $orderTypeName,
            'date' => date('Y-m-d H:i:s',time()),
            'order_id'=>$orderId,
        ]);

        //发送分红短信给合伙人
        $this->sendOrderGrossNoticePartner($partner->mobile,$commission);

        return true;
    }
    //股东业绩
    private function  shareholderCommission($partner,$mid,$money,$orderTypeName,$description,$orderId=0){
        $share_capital = $partner->share_capital;
        if(empty($this->setting->dividend_ratio_data)) return false;
        $commissionRate = 0;
        foreach($this->setting->dividend_ratio_data as $val){
            if($val['share_capital'] <= $share_capital && $val['dividend_ratio'] >= $commissionRate){
                $commissionRate =  $val['dividend_ratio'];
            }
        }
        if(empty($commissionRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = round(($partner->withdrawable_profit *  100  + $commission * 100)/100,2);
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'description' => $description,
            'type'       => $orderTypeName,
            'date' => date('Y-m-d H:i:s',time()),
            'order_id'=>$orderId,
        ]);

        //发送分红短信给合伙人
        $this->sendOrderGrossNoticePartner($partner->mobile,$commission);

        return true;
    }

    private function customCommission($partner,$mid,$money,$orderTypeName,$description,$orderId=0)
    {
        $commissionRate=$partner->custom_rate;
        if(empty($commissionRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false;
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = 0; //不可提现
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'type'       => $orderTypeName,
            'description' => $description,
            'date' => date('Y-m-d H:i:s',time()),
            'order_id'=>$orderId,
        ]);

        //发送分红短信给合伙人
        $this->sendOrderGrossNoticePartner($partner->mobile,$commission);

        return true;
    }
    
    
    /**
     * @params  $memberId,$pid, $isNew 是否是新用户
     * @return  bool  
     */
    public function bindPartner($memberId,$pid,$isNew = true){
        if(empty($pid)) return false;
        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        $MemberModel = new MemberModel();
        if(null === $member = $MemberModel->find($memberId)) return false;
        if($member->pid != 0) return false; //父级ID 不为空

        if(null === $pmember = MemberModel::find($pid)) return false;

        $partner = PartnerModel::where([
            ['shop_id','=',$this->shopId],
            ['mobile','=',$pmember->mobile],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;

        $partner_setting_status=false;
        if($partner->role_id==1 && $this->setting->is_bind_shareholder==1) $partner_setting_status=true;
        if($partner->role_id==2 &&  $this->setting->is_bind_employee==1) $partner_setting_status=true;
        if($partner->role_id==3) $partner_setting_status=true;
        if($partner->role_id==4) $partner_setting_status=true;
        if($isNew || $partner_setting_status){
            $member->pid=$pid;
            $member->save();
            return  true;
        }
        return false;
    }
    public function bindPartnerStores($memberId,$pid,$isNew = true,$giftbag_id=0){
        if(empty($pid)) return false;
//        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        $MemberModel = new MemberModel();
        if(null === $member = $MemberModel->find($memberId)) return false;
        if($member->pid != 0) return false; //父级ID 不为空

        if(null === $pmember = MemberModel::find($pid)) return false;

        $partner = PartnerModel::where([
            ['shop_id','=',$this->shopId],
            ['member_id','=',$pmember->member_id],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;
        if($isNew){
            $member->pid=$pid;
            $member->partner_id=$partner['partner_id'];
            $member->save();
            $share_in['shop_id']=$this->shopId;
            $share_in['member_id']=$memberId;
            $share_in['partner_id']=$partner['partner_id'];
            $share_in['giftbag_id']=$giftbag_id;
            $share_in['type']=1;
            $share_in['is_new']=1;
            $share_in['is_receive']=1;
            $share_in['add_time']=date('Y-m-d H:i:s');
            PartnerShareModel::insert($share_in);
            return  true;
        }
        return false;
    }

    /**
     * 毛利分红
     * @params $memberId,$money
     * @return  bool
     */
    public function  commissionNew($memberId,$money,$ordertable,$orderId=0){

        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        if($money <= 0) return false;
        $pid  = $mid = 0; $mobile = '';
        if(is_numeric($memberId)){
            $member = MemberModel::find($memberId);
            if(null === $member) return false;
            $pid = $member->pid;
            $mid = $memberId;

            //购买者手机号
            $buyer_mobile = $member->mobile;
        }else{
            $pid = $memberId->pid;
            $mid = $memberId->member_id;
            //购买者手机号
            $buyer_mobile = $memberId->mobile;
        }

        if(empty($pid)) return false;

        $orderType = [
            'cashierOrder' => '收银台',
            'order' => '普通订单',
            'storeOrder' => '普通订单',
            'memberOnceCard' => '购买次卡',
            'onceCardOrder' => '购买次卡',
            'snapUpOrder' => '抢购项目订单',
            'pintuanOrder' => '拼团订单',
            'supplement' => '线下补单',

        ];

        $orderTypeName = $orderType[$ordertable];

        $description = $money;

        $pmemberModel = new MemberModel();
        if(null === $pmember = $pmemberModel->find($pid)) return false;
        $partner = PartnerModel::where([
            ['mobile','=',$pmember->mobile],
            ['shop_id','=', $this->shopId],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;

        //商品毛利分红,分红金额按照商品毛利加总算
        if($this->setting->dividend_type == 2){
            if($ordertable == 'cashierOrder') {
                //收银台支付订单
                $items= new CashierOrderItemModel();
                $items=$items->where([

                    ['shop_id','=',$this->shopId],

                    ['order_id','=',$orderId]

                ])->field('goods_gross,goods_num')->select()->toArray();

                $goods_gross_money = 0;
                foreach ($items as $item){
                    $goods_gross_money += $item['goods_gross'] * $item['goods_num'];
                }

                //毛利商品金额
                $money = $goods_gross_money;

            }elseif($ordertable == 'order'){
                //小程序支付订单
                $items= new GoodsOrderItemModel();

                $items=$items->where([

                    ['shop_id','=',$this->shopId],

                    ['order_id','=',$orderId]

                ])->field('goods_gross,goods_num')->select()->toArray();

                $goods_gross_money = 0;
                foreach ($items as $item){
                    $goods_gross_money += $item['goods_gross'] * $item['goods_num'];
                }
                //毛利商品金额
                $money = $goods_gross_money;

            }elseif($ordertable == 'storeOrder'){
                //囤货订单：毛利从囤货设置里取，生成订单
                $goods_gross = StoreOrderModel::where('store_order_id',$orderId)->value('goods_gross');
                //毛利商品金额
                $money = $goods_gross;
            }elseif($ordertable == 'memberOnceCard'){
                //pc会员购买次卡，毛利商品金额
                $money = $orderId;
            }elseif($ordertable == 'onceCardOrder'){
                //小程序购买次卡，毛利商品金额
                $gross = OnceCardOrderModel::where('once_card_order_id',$orderId)->value('gross');
                //毛利商品金额
                $money = $gross;
            }elseif($ordertable == 'snapUpOrder'){
                //小程序抢购项目，毛利商品金额
                $gross = SnapUpOrderModel::where('snap_up_order_id',$orderId)->value('gross');
                //毛利商品金额
                $money = $gross;
            }elseif($ordertable == 'pintuanOrder'){
                //拼团支付订单
                $items= new PinTuanOrderItemModel();

                $items=$items->where([

                    ['shop_id','=',$this->shopId],

                    ['pin_tuan_order_id','=',$orderId]

                ])->field('goods_gross,goods_num')->select()->toArray();

                $goods_gross_money = 0;
                foreach ($items as $item){
                    $goods_gross_money += $item['goods_gross'] * $item['goods_num'];
                }
                //毛利商品金额
                $money = $goods_gross_money;

            }elseif($ordertable == 'supplement'){
                //线下补单毛利商品金额
                $money = $orderId;
            }


        }

        switch($partner->role_id){
            case 1: //股东
                return  $this->shareholderCommission($partner, $mid, $money,$orderTypeName,$description,$orderId);
                break;
            case 2://员工
                return  $this->staffCommission($partner, $mid, $money,$orderTypeName,$description,$orderId);
                break;
            case 3://会员
                return  $this->memberCommission($partner, $mid, $money,$orderTypeName,$description,$orderId);
                break;
            case 4://自定义
                return  $this->customCommission($partner, $mid, $money,$orderTypeName,$description,$orderId);
                break;
        }


        return true;

    }


    //发送短信给合伙人
    public function sendOrderGrossNoticePartner($mobile,$gross)
    {
        $sms_setting = SettingSmsModel::where([['shop_id','=',$this->shopId]])->find();

        if(null !== $sms_setting) {

            $sms_logic = new SmsLogic();

            $params = [

                'gross' => $gross,

            ];

            $sms_logic->send($this->shopId, [$mobile], $params, 'orderGrossNoticePartner');

            /*$params=[

                'xm'=>$gross,

            ];

            $sms_logic->send($this->shopId,[$mobile],$params,'cancelAppointment');*/

        }
    }
    
}